<?php
 include "counter.php";
	
// parameters
$place = $counter->get_input("place", "place", "get");
$find = $counter->get_input("find", "", "post");

function locate_place($sql, $placeid) {


	global $find;
	global $find_like;
	global $place_rows;

print "<!-- $sql -->\n";
 	$placeq = mysql_query($sql);
	if ( $place_rows = mysql_num_rows($placeq) ) {
 		$place = mysql_fetch_array($placeq);
	 	while ( $place['type'] == "alias" ) {
 		 	$placeq = mysql_query("select * from places where ".
				 	"f_key = '". $place['within']."'");
 		 	$place = mysql_fetch_array($placeq);
	 	}
	}
	if ( !$find && $place_rows > 1 ) {
		$find = ereg_replace(".*:", "", $placeid);
	}
print "<!-- sql found = $place_rows rows -->\n";
	return $place;
}

 if (!$columns) {
    $columns = 3;
 }
 if (!$place) {
    $place = "All";
 }
$find_like = "=";
 if ( $find ) {
        # Check if a very narrow search had exactly one result.
        # In that case, go straight there.
	$findq =  mysql_query("select * from places where name like
	'%:$find' or name = '$find' or longname = '$find'");
	if ( mysql_num_rows($findq) == 1 ) {
		  $found = mysql_fetch_array($findq);   
		while ( $found['type'] == "alias" ) {
			$findq =  mysql_query("select * from places where f_key = '".$found['within']."'"); 
			 $found = mysql_fetch_array($findq);
		}
		$place=$found['name'];
		$find="";
	}
}

	$place_hold = $place;
 	$placeq = "select * from places where name = '$place'";
	$place_res = locate_place($placeq, $place);
	if ( ! $place_res) {
		$place_new = ereg_replace(":.*:", ":%:", $place);
 		$placeq = "select * from places where name like '$place_new'";
 		$place_res = locate_place($placeq, $place_new);
	}
	if ( ! $place_res) {
		list ($country, $state, $city) = split(":", $place);
 		$placeq = "select * from places where name = '$country:$state'";
 		$place_res = locate_place($placeq, "$country:$state");
	}
	if ( ! $place_res) {
 		$placeq = "select * from places where name like '%:$state:$city'";
 		$place_res = locate_place($placeq, $city);
	}
	if ( ! $place_res) {
 		$placeq = "select * from places where name like '%:$state'";
 		$place_res = locate_place($placeq, $state);
		if (  $place_res) {
			$cc = ereg_replace(":.*", "", $place_res['name']);
			$placeq = "select * from places where name = '$cc::$city'";
			$place_res = locate_place($placeq, $state);
		}
	}
	if ( ! $place_res) {  
 		$placeq = "select * from places where name = '$country'";
 		$place_res = locate_place($placeq, $county);
	}
	if ( ! $place_res ) {
		if ( ! $find ) {
			$find = $city;
		}
		$placeq = "select * from places where name = 'all'";
                $place_res = locate_place($placeq, "All"); 
	}
	$place = $place_res;

     
function page_bar($personcount, $quotedname) {
 global $PHP_SELF;
 if ( $personcount > 90 ) {
        $page_no = 0;
        while ( ( $page_no * 90 ) < $personcount ) {
                if ( ! $page_no ) {
                        print "[ <a href=\"".$PHP_SELF."?place=$quotedname\">First</a>";
                } else if ( (($page_no * 90 ) + 90) > $personcount ) {
                        print " | <a href=\"$PHP_SELF?place=$quotedname&page=$page_no\">Last</a> ]";
                } else {
                        print " | <a href=\"$PHP_SELF?place=$quotedname&page=".
                                $page_no."\">Page ".($page_no + 1)."</a>";
                }
                $page_no++;
        }
      }
}
?>
<?php pagehead("Information about ".$place['longname']) ?>
<BODY bgcolor="white">
<?php pagetop() ?>
<table>
<tr><th>Seach for a place<td><form action="<?php echo $PHP_SELF ?>" method=post>
<input type=text name=find size=20>
<input type=submit value="Go">
</form>
</table>
<?php
 if ( $find ) {
        # note: this search is wider than the one further up the page.
        # so it's possible to find more here.
	$findq =  mysql_query("select * from places where name like
              '%$find%' or longname like '%$find%'
		order by name");
	if ( mysql_num_rows($findq) > 1 ) {
		print "<table><tr><th align=left>Search results for $find";
		while ( $found = mysql_fetch_array($findq) ) {
			print "<tr><td>";
			place_bar ($found, 1);
		}   
		print "</table>";	
	} else { 
		print "Search results<br>Nothing found for $find";
	}
}
?>
<h1>
Linux users in <?php echo $place['longname'] ?></h1>
<?php place_bar($place); ?>
<BR>
<img src="/gifs/Logo-small.png" alt="Linux Counter Logo" align="top">


<?php
 $lowname = strtolower($place['name']);
 if (file_exists($homedir . "/www/bycountry/$lowname.png")) {
      echo "<img src=\"/bycountry/$lowname.png\"><p>\n";
 } else {
# note: the tempplot is generated on-demand using mod_rewrite
    echo "<img src=\"/tempplots/" . urlencode($place['name']) . ".png\"><p>\n";
}
 

?>
<font size=-2><a href="/legal.php">Copyright &copy; Linux Counter Project. Usage
restricted.</a></font><br>
<?php 
 $place_html = ereg_replace(".*html:", "", $place['f_clean']);
 if (  $place_html != $place['f_clean'] ) {
 	print "$place_html<br clear=all>";
 }
?>

<table border=0 width="80%">
<tr><td>
<table>
<tr><th align=right>Place code:</th><td><?php echo $place['name'] ?></td></tr>
<tr><th align=right>Maintainer(s):</th><td><?php print findmaintainer($place) ?></td></tr>
<tr><th align=right>Population:</th><td><?php echo
$place['population']?$place['population'] . "million":"Not set" ?></td></tr>
<tr><th align=right>Hostcount:</th><td><?php echo $place['hostcount'] ?></td></tr>
<tr><th align=right>Linux users:</th><td><?php echo $place['users'] ?></td></tr>
<?php 
if ($place['population'] > 0) {
   printf("<tr><th align=right>Linux density:</th><td>%5.2f users/million</td></tr>", $place['users'] / $place['population']);
}
if ($place['hostcount'] > 0) {
    printf("<tr><th align=right>Linux users per 1000 IP hosts:</th><td>%5.2f</td></tr>",
	$place['users'] * 1000/ $place['hostcount']);
}

print "</table><p>";
if ($place['type'] == "country" && $place['users'] > 0) {
   $tq = mysql_query("select * from temp_short where country = '".
							$place['name']."'");
   $td = mysql_fetch_array($tq);
   printf ( "%s is no. %s in the density statistics, with %s users/Mpop<br>\n",
   		$place['longname'], 
		$td['rank'], 
		$td['userdensity']);
   // print $place['longname']." is no. ".$td['rank']." in the density statistics, with ".$td['userdensity']." users/Mpop<br>\n";
   if ($td['rank'] > 1) {
      $tq = mysql_query("select * from temp_short where rank = " . ($td['rank'] - 1));
   if ($tq == 0) {
       print("</table>MySQL error: " . mysql_errno() . ":" . mysql_error());
       die("Query for count failed");
    }                                                                                                          
      $tdup = mysql_fetch_array($tq);
      $need = $tdup['userdensity'] * $td['population'] - $td['users'] + 1;
      printf("%s needs %d more users to pass %s and become no. %d<br>\n",
      		$place['longname'],
	      $need, placeurl($tdup['country'], $tdup['name']), $td['rank'] - 1);
   }
   $tq = mysql_query("select * from temp_short where rank = " . ($td['rank'] + 1));
   if (mysql_num_rows($tq) > 0) {
      $tdown = mysql_fetch_array($tq);
      $need = $td['userdensity'] * $tdown['population'] - $tdown['users'] + 1;
      printf("%s needs %d more users to pass %s and become no. %d<br>\n",
	      placeurl($tdown['country'], $tdown['name']), $need, $td['name'], $td['rank']);
   }
} 
if ($place['within'] != 0) {
   $uq = mysql_query("select * from places where f_key = " . $place['within']);
   $upper = mysql_fetch_array($uq);
//   printf("$place['longname'] is part of %s<br>\n", placeurl($upper['name'], $upper['longname']));
}
?>
</table>

<!-- Subordinate places -->
<?php
function uindex ($personcount, $place, $quotedplace) {

 global $PHP_SELF;  
	if ( $personcount < 91 ) {
		return;
	}
	$alphaq = mysql_query(
           "select substring(name, 1, 1) as c from persons
                   where placeid = '$quotedplace'
		   and may_publish = 'YES'
	           group by c");
	print "<h4>";
        while ($alpha = mysql_fetch_row($alphaq)) {
            $a = strtoupper($alpha['0']);
	    if ( $a >= "A" && $a <= "Z" ) {
	    	print "<a href=\"$PHP_SELF?start=$a&place=".
			urlencode($quotedplace).
			"#person\">$a</a> &nbsp; ";
	    }
        }
        print "</h4><p>";
}

function presentlist($type, $title) {

   global $PHP_SELF;
   global $place;
   global $columns;

   $col = floor($columns/2);
   if ($col == 0) { $col = 1; }

   $places = mysql_query("select * from places where within = ".
			$place['f_key'].
			" and type = '$type' and users > 0 order by longname");
   if (mysql_num_rows($places) == 0) { return; }
   print "<h2>$title within ".$place['longname']."</h2>\n";
   if (mysql_num_rows($places) > 20) {
	$alphaq = mysql_query(
           "select substring(longname, 1, 1) as c from places
                   where within = ". $place['f_key'].
		   " and type = '$type' and users > 0
	           group by c");
	print "<h4>";
	$expect = "A";
	$previous = "@";
        while ($alpha = mysql_fetch_row($alphaq)) {
            $a = strtoupper($alpha['0']);
	    if ( $a > "Z" ) {
	    	$previous++;
		$a = $previous;
 	    }
	    print "\n<a href=\"#place_".$type."_$a\">$a</a> &nbsp; ";
	    $previous = $a;
        }
        print "</h4><p>";
   }
   print "<table>\n";
   $preva = "";
   print "<tr>";
   for ($itemcount=0; $itemcount <= $col; $itemcount += 2) {
	print "<th align=left>Name</th><th>Users</th>\n";
   }
   $itemcount = 0;
   while ($sub = mysql_fetch_array($places)) {
       $placeurl = urlencode($sub['name']);
       $a = strtoupper(substr($sub['longname'], 0, 1));
       if ($itemcount % $col == 0) {
 	  print "<tr>";
       }
       ++ $itemcount;
       print "<td>";
       if ( $a > "Z" ) {
		$a = $preva;
       }
       if ($a > $preva) {
	   print "<a name=\"place_".$type."_$a\"> </a>";
           $preva = $a;
       }
       print "<a href=\"$PHP_SELF?place=$placeurl\">".$sub['longname']."</a>";
       print "<td align=right>".$sub['users']."<br>\n";
   }
   print "</table>\n";
}
?>

<?php
  presentlist("country", "Countries");
  presentlist("state", "States/Regions");
  presentlist("city", "Cities");
?>

<!-- Subordinate persons -->
<?php
if  ( $people != "no" ) {
  $quotedname = mysql_escape_string($place['name']);
  $totalcount   = dbcount("persons", "placeid = '$quotedname'");
  $privatecount = dbcount("persons",
			"placeid = '$quotedname' and  may_publish = 'NO'");
  $personcount  = dbcount("persons",
			"placeid = '$quotedname' and  may_publish = 'YES'");
  if ($personcount > 90) {
      $start_after = urldecode($next);
      if ($page) {
	$start=$page*90;
	$end = $start + 90;
	if ( $end > $personcount ) {
		$end = $personcount;
	}
      $note = "Listing users $start to $end of $personcount registered persons.";
      $persons = mysql_query("select * from persons
                          where placeid = '$quotedname' 
				and may_publish = 'YES'
                          order by name limit $start,90");
      } elseif ($start)  {
//      $note = "Listing the first 90 of $personcount registered persons.";
      $persons = mysql_query("select * from persons
                          where placeid = '$quotedname' 
				and name >= '$start'
				and may_publish = 'YES'
                          order by name limit 90");
      } else {
	 $note = "Listing the first 90 of $personcount registered persons.";
      $persons = mysql_query("select * from persons
                          where placeid = '$quotedname'
                                and may_publish = 'YES'
                          order by name limit 90");
      }
  } else {
      $note = "Listing $personcount registered persons.";
      $persons = mysql_query("select * from persons
                          where placeid = '$quotedname'
				and may_publish = 'YES'
                          order by name");
   }
   if (mysql_num_rows($persons) > 0) {
      print "<a name=person></a><h2>Persons within ".$place['longname']."</h2>\n";
      print $note;
      if ( $privatecount > 0 ) {
        if ( $privatecount > 1 ) {
      	  printf ("<br>There are also %d registered persons who do not wish to be listed<hr>", $privatecount);
        } else {
          printf ("<br>There is also %d registered person who does not wish to be listed<hr>", $privatecount);
        }
      }
      page_bar($personcount, $quotedname);
      uindex($personcount, $place, $quotedname);
?>
<?php
      if ( $personcount < 20 ) {
	$columns = 1;
      }
      # damn Netscape....must respect margin..
}
?>
<p><table width="95%">
<?php
      $itemcount = 0;
      while ($sub = mysql_fetch_array($persons)) {
             if ($itemcount++ % $columns == 0) {
     	        print "<tr>";
             }
   	     printf("<td width=\"%d%%\">%s\n",
				50/$columns,
		person_url($sub['f_key'], $sub['name']));
	   $home_page = ereg_replace(".*homepage:", "", $sub['f_raw']);
	     if ( $home_page  != $sub['f_raw'] ) {
	    	$home_page = ereg_replace("ident:.*", "", $home_page);
		   if ( ! preg_match("/^http:\/\//", $home_page ) ) {
			$home_page = "http://".$home_page;
		   }
		   printf ("<td width=\"%d%%\"><a href=\"%s\" target=\"_blank\">%s</a>", 50/$columns, $home_page, "<img src=\"/gifs/house.png\" alt=\"User homepage logo\" border=\"0\" valign=\"middle\">");
	      } else {
		    printf ("<td width=\"%d%%\">", 50/$columns);
	      }
      }
	print "</table>";
   }
?>
<p>
<?php
page_bar($personcount, $quotedname);
pagebottom()
?>
</body>
</html>
